<template>
   <a-upload
      v-model:file-list="fileList"
      action="http://localhost:8081/api/upload/file"
      name="file"
      list-type="picture-card"
      @preview="handlePreview"
      @change="handleChange"  
      @remove="removeImage"
    >
    
      <div v-if="(fileList && fileList.length<maxcount) || !currentImages">
        <plus-outlined />
        <div style="margin-top: 8px">上传</div>
      </div>
    </a-upload>

     <a-modal :open="previewVisible"  :footer="null" @cancel="handleCancel">
      <img alt="example" style="width: 100%" :src="previewImage" />
    </a-modal>

</template>

<script  setup>
import { reactive,ref, watch , nextTick} from 'vue'
import { PlusOutlined } from '@ant-design/icons-vue';

const props = defineProps({
  currentImages:Array,
  maxcount:{
    type:Number,
    default:1
  }
})

const emit = defineEmits(['success'])
// fileList: 主要是用来做图片预览的变量
const fileList = ref([
  // {
  //   url: 'https://zos.alipayobjects.com/rmsportal/jkjgkEfvpUPVyRjUImniVslZfWPnJuuZ.png',
  // },
  // {
  //   url: 'http://localhost:3000/upload/1756174572675.png',
  // }
])

watch(()=>props.currentImages,(newImgs)=>{
  
  const arrList =  newImgs?.reduce((pre, next, index)=>{
    if(pre) {
          pre.push({
            uid:index+'',
            name: next,
            url: `http://localhost:8081/uploads/`+next
          })
    }
      return pre
   },[])

   successFiles.value = newImgs;   // 编辑的时候， 把已经存在的图片 初始化给 successFiles
   nextTick(()=>{
         fileList.value = arrList
   })
  })

// 删除图片
function removeImage(file){
  let filename = ''
  if(file.url){
     filename =   file.url.split('/').pop()
  } else {
    filename = file.response.data    // 刚上传图片
  }
 
  const restImages =  props.currentImages?.filter((item)=>{
        return item!=filename
    })
 
 // 把剩余的图片 传到父组件
//  successFiles.value
  emit('success', restImages)   // 给父组件发送数据
}
// 图片源信息传华为base64
function getBase64(file) {
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = () => resolve(reader.result);
    reader.onerror = error => reject(error);
  });
}

// 浏览图片
const previewVisible = ref(false)
const previewImage = ref('') // 当前要预览的图片
const handlePreview = async (file) => {
    previewVisible.value = true

  if (!file.url && !file.preview) {
    file.preview = (await getBase64(file.originFileObj));
  }
    previewImage.value =  file.url || file.preview
}

// 关闭图片的预览
const handleCancel = ()=>{
    previewVisible.value = false
}

const successFiles = ref([])      //在添加新闻的时候 需要给到后端
const handleChange = (info)=>{
    if (info.file.status === 'done') { 
            // 图片上传成功
       console.log(info.file.response,'==========');  // 图片上传成功后， 接口返回的数据
       successFiles.value.push(info.file.response.data)  

       emit('success', successFiles.value)   // 给父组件发送数据

    }

}


</script>

<style lang='scss' scoped>
</style>